﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using olierFrm.DataBase;
using olierFrm.DataBase.FrameWork;
using olierFrm.DataBase.FrameWork.Business;
using olierFrm.DataBase.FrameWork.DataObject;
using olierFrm.DataBase.FrameWork.Plugin;
using olierFrm.DataBase.FrameWork.StdQuery;
using olierFrm.Extensions.EString;

namespace olierFrm.MVC
{
    public static class SmartPage
    {
        public class PostResult
        {
            public System.Collections.Generic.List<string> ErrorFields
            {
                get;
                set;
            }
            public string Message
            {
                get;
                set;
            }
            public string ToUrl
            {
                get;
                set;
            }
            public bool Success
            {
                get;
                set;
            }
            public Dictionary<string, object> OutPut { get; set; }
        }
        public class SmartPageEntity
        {
            public System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<WF_SmartQueryParams>> StdQueryParams
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, WF_SmartQuery> StdQuery
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, WF_DataObject> DataObject
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<WF_DataObjectParams>> DataObjectParams
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, WF_Business> Business
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<WF_BusinessParams>> BusinessParams
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<WS_CommonItems>> Common
            {
                get;
                set;
            }
            public ReceiptsConfigObject ConfigObject
            {
                get;
                set;
            }
        }
        public class SmartPageData
        {
            private string _LoginUser;
            public SmartPage.SmartPageEntity Entity
            {
                get;
                set;
            }
            public DataSet StdQuery
            {
                get;
                set;
            }
            public DataSet StdQueryParams
            {
                get;
                set;
            }
            public DataSet StdQuerySum
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>> Common
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, string> Business
            {
                get;
                set;
            }
            public System.Collections.Generic.Dictionary<string, DataSet> DataObject
            {
                get;
                set;
            }
            public ActionPageParams.Get Get
            {
                get;
                set;
            }
            public string LoginUser
            {
                get
                {
                    if (this._LoginUser == string.Empty && System.Web.HttpContext.Current.Session["LoginUserName"] != null)
                    {
                        this._LoginUser = System.Web.HttpContext.Current.Session["LoginUserName"].ToString();
                    }
                    return this._LoginUser;
                }
            }
            public string Cookie
            {
                get
                {
                    return "";
                }
            }
        }
        public static SmartPage.PostResult ExecuteBusiness(ActionPageParams.Post pp)
        {
            SmartPage.PostResult pr = new SmartPage.PostResult();
            pr.Message = "success";
            pr.Success = true;
            if (pr.OutPut == null) pr.OutPut = new Dictionary<string, object>();
            pr.ToUrl = pp.ToUrl;
            try
            {
                BusinessSQL bs = new BusinessSQL(pp.SqlID);

                System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
                if (bs.BusinessParams != null)
                {
                    System.Collections.Generic.List<object> listParams = (System.Collections.Generic.List<object>)pp[pp.SqlID];
                    System.Collections.Generic.Dictionary<string, object> masterParams = (System.Collections.Generic.Dictionary<string, object>)listParams[0];
                    foreach (System.Collections.Generic.KeyValuePair<string, object> i in masterParams)
                    {
                        if (bs.FindParamByName(i.Key) != null)
                        {

                            bs.SetParam(i.Key, i.Value);
                        }
                    }
                    System.Collections.Generic.List<string> UFValues = "I;U;D".Split(new char[]
					{
						';'
					}).ToList<string>();
                    for (int j = 1; j < listParams.Count; j++)
                    {
                        string strUpdateFlag = "UpdateFlag";
                        if (j > 1)
                        {
                            strUpdateFlag += j;
                        }
                        System.Collections.Generic.List<object> detail = (System.Collections.Generic.List<object>)listParams[j];
                        for (int d = 0; d < detail.Count; d++)
                        {
                            System.Collections.Generic.Dictionary<string, object> fields = (System.Collections.Generic.Dictionary<string, object>)detail[d];
                            if (!fields.ContainsKey(strUpdateFlag) || UFValues.IndexOf(fields[strUpdateFlag].ToString()) != -1)
                            {
                                foreach (System.Collections.Generic.KeyValuePair<string, object> k in fields)
                                {
                                    if (bs.FindParamByName(k.Key) != null)
                                    {
                                        bs.AddParam(k.Key, k.Value);
                                    }
                                }
                            }
                        }
                    }
                }
                bs.AddSystemParams();
                bs.ExecuteSQL();
                var outputParams = bs.ObjectSQLParam.Where(p => p.OutPut);
                var pps = (System.Collections.Generic.List<object>)pp[pp.SqlID];
                var master = (System.Collections.Generic.Dictionary<string, object>)pps[0];

                foreach (var p in outputParams)
                {
                    if (p.ParamType.IndexOf("DateTime") != -1)
                    {
                        pr.OutPut.Add(p.ParamName, p.ParamValue.ToLongDateTime());
                    }
                    else
                    {
                        pr.OutPut.Add(p.ParamName, p.ParamValue);
                    }

                    master[p.ParamName] = p.ParamValue;
                }
            }
            catch (System.Exception e)
            {
                pr.Message = e.Message;
                pr.Success = false;
            }
            return pr;
        }
        public static SmartPage.SmartPageData GetSmartPageData(System.Web.Routing.RouteData routeData)
        {
            SmartPage.SmartPageData smartPageData = new SmartPage.SmartPageData();
            smartPageData.Get = new ActionPageParams.Get(routeData);
            if (System.Web.HttpContext.Current.Request.QueryString["autoSearch"] == null)
            {
                smartPageData.Entity = new SmartPage.SmartPageEntity();
                smartPageData.Entity.ConfigObject = new ReceiptsConfigObject();
                var cc = routeData.Values["CustController"] == null ? "" : routeData.Values["CustController"] + "/";
                SmartPage.LoadReceiptsConfig(cc + routeData.Values["Module"], smartPageData.Entity.ConfigObject);
                SmartPage.LoadStdQuery(smartPageData);
                SmartPage.LoadDataObject(smartPageData);
                SmartPage.LoadBusiness(smartPageData);
                SmartPage.LoadCommon(smartPageData);
            }
            routeData.Values["controller"] = smartPageData.Get.CustController;
            routeData.Values["action"] = smartPageData.Get.Module;
            return smartPageData;
        }

        public static SmartPage.SmartPageData GetSmartPageData(string module, string page, System.Web.Routing.RouteData routeData)
        {
            routeData.Values["CustController"] = module;
            routeData.Values["Module"] = page;
            return GetSmartPageData(routeData);
        }


        private static void LoadCommon(SmartPage.SmartPageData smartPageData)
        {
            ReceiptsConfigObject co = smartPageData.Entity.ConfigObject;
            if (co.Common != null)
            {
                smartPageData.Entity.Common = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<WS_CommonItems>>();
                smartPageData.Common = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>();
                foreach (string c in co.Common)
                {
                    System.Collections.Generic.List<WS_CommonItems> commons = Common.FindByCommonNO(c);
                    smartPageData.Entity.Common.Add(c, commons);
                    smartPageData.Common.Add(c, commons.ToDictionary((WS_CommonItems k) => k.sComID, (WS_CommonItems v) => v.sComDesc));
                }
            }
        }
        private static void LoadBusiness(SmartPage.SmartPageData smartPageData)
        {
            ReceiptsConfigObject co = smartPageData.Entity.ConfigObject;
            if (co.Business != null)
            {
                smartPageData.Business = co.Business;
            }
        }
        private static void LoadStdQuery(SmartPage.SmartPageData smartPageData)
        {
            ReceiptsConfigObject co = smartPageData.Entity.ConfigObject;
            if (co.StdQuery != null && co.StdQuery.SqlID != null)
            {
                smartPageData.StdQuery = new DataSet();
                smartPageData.StdQuerySum = new DataSet();
                smartPageData.Entity.StdQuery = new System.Collections.Generic.Dictionary<string, WF_SmartQuery>();
                smartPageData.Entity.StdQueryParams = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<WF_SmartQueryParams>>();
                foreach (string s in co.StdQuery.SqlID)
                {
                    if (s.Trim().Length != 0)
                    {
                        StdQuerySQL std = new StdQuerySQL(s);

                        smartPageData.Entity.StdQuery.Add(s, std.StdQuery);
                        smartPageData.Entity.StdQueryParams.Add(s, std.StdQueryParams);
                        foreach (WF_SmartQueryParams p in std.StdQueryParams)
                        {
                            string pv = System.Web.HttpContext.Current.Request.QueryString[p.ParamName];
                            if (pv != null)
                            {
                                std.SetParam(p.ParamName, pv);
                            }
                        }
                        DataTable dt = null;
                        std.AddSystemParams();
                        if (System.Web.HttpContext.Current.Request.QueryString[std.StdQuery.QueryName + "Page"] != null ||
                            std.StdQuery.SQL.IndexOf("--STARTPAGING", System.StringComparison.CurrentCultureIgnoreCase) != -1
                            )
                        {
                            int start = System.Convert.ToInt32(System.Web.HttpContext.Current.Request.QueryString[std.StdQuery.QueryName + "Page"]);
                            start *= 10;
                            if (std.StdQuery.SQL.IndexOf("--STARTPAGING", System.StringComparison.CurrentCultureIgnoreCase) != -1)
                            {

                                dt = std.AutoPagingExecuteSQL((start+1), start + 10);
                            }
                            else
                            {
                                dt = std.ExecuteSQL((start + 1), start + 10);
                            }

                        }
                        else
                        {

                            dt = std.ExecuteSQL();
                        }
                        if (olierFrm.MVC.Config.DataDictionary)
                            dt.BindCaptionToDataTable();
                        smartPageData.StdQuery.Tables.Add(dt);
                        DataTable dtsumsql = std.ExecuteSumSQL();
                        if (dtsumsql != null)
                        {
                            smartPageData.StdQuerySum.Tables.Add(dtsumsql);
                        }

                    }
                }
            }
        }
        private static void LoadDataObject(SmartPage.SmartPageData smartPageData)
        {
            ReceiptsConfigObject co = smartPageData.Entity.ConfigObject;
            if (co.DataObject != null && co.DataObject.SqlID != null)
            {
                smartPageData.DataObject = new Dictionary<string, DataSet>();
                smartPageData.Entity.DataObject = new Dictionary<string, WF_DataObject>();
                smartPageData.Entity.DataObjectParams = new Dictionary<string, List<WF_DataObjectParams>>();
                foreach (string s in co.DataObject.SqlID)
                {
                    if (s.Trim().Length != 0)
                    {
                        DataObjectSQL dos = new DataObjectSQL(s);
                        smartPageData.Entity.DataObject.Add(s, dos.DataObject);
                        smartPageData.Entity.DataObjectParams.Add(s, dos.DataObjectParams);
                        foreach (WF_DataObjectParams p in dos.DataObjectParams)
                        {
                            string pv = System.Web.HttpContext.Current.Request.QueryString[p.ParamName];
                            if (pv != null)
                            {
                                dos.SetParam(p.ParamName, pv);
                            }
                        }
                        dos.AddSystemParams();
                        DataSet ds = dos.ExecuteSQL();
                        if (olierFrm.MVC.Config.DataDictionary)
                        {
                            for (int i = 0; i < ds.Tables.Count; i++)
                            {
                                ds.Tables[i].BindCaptionToDataTable();
                            }
                        }
                        smartPageData.DataObject.Add(s, ds);

                    }
                }
            }
        }
        private static List<string> GetProperty(ReceiptsConfig rc, string sConfig, string section, string key)
        {
            string value = rc.GetPrivateProfileString(section, key);
            System.Collections.Generic.List<string> result;
            if (value != null)
            {
                result = value.Split(new char[]
				{
					';'
				}).ToList<string>();
            }
            else
            {
                result = null;
            }
            return result;
        }
        private static void Test(ReceiptsConfigObject rco, ReceiptsConfig rc, string sConfig, string property)
        {
            System.Collections.Generic.List<string> SqlIDList = SmartPage.GetProperty(rc, sConfig, property, "SqlID");
            if (SqlIDList != null)
            {
                string AddScript = rc.GetPrivateProfileString(property, "Add");
                string ModifyScript = rc.GetPrivateProfileString(property, "Modify");
                string DelScript = rc.GetPrivateProfileString(property, "Del");
                System.Collections.Generic.List<string> CheckScript = new System.Collections.Generic.List<string>();
                int chkIndex = 0;
                while (true)
                {
                    string c = rc.GetPrivateProfileString(property, "CHECK_" + chkIndex);
                    if (c == null || c.Length == 0)
                    {
                        break;
                    }
                    CheckScript.Add(c);
                    chkIndex++;
                }
                object stdquery = rco.GetType().GetProperty(property).GetValue(rco, null);
                stdquery.GetType().GetProperty("SqlID").SetValue(stdquery, SqlIDList, null);
                System.Collections.Generic.List<string> add = SmartPage.GetProperty(rc, sConfig, property, "Add");
                System.Collections.Generic.List<string> modify = SmartPage.GetProperty(rc, sConfig, property, "Modify");
                System.Collections.Generic.List<string> del = SmartPage.GetProperty(rc, sConfig, property, "Del");
                System.Collections.Generic.Dictionary<string, string> diAdd = new System.Collections.Generic.Dictionary<string, string>();
                System.Collections.Generic.Dictionary<string, string> diModify = new System.Collections.Generic.Dictionary<string, string>();
                System.Collections.Generic.Dictionary<string, string> diDel = new System.Collections.Generic.Dictionary<string, string>();
                System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> diCheck = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>>();
                for (int i = 0; i < SqlIDList.Count; i++)
                {
                    if (add != null)
                    {
                        diAdd.Add(SqlIDList[i], add[i]);
                    }
                    if (modify != null)
                    {
                        diModify.Add(SqlIDList[i], modify[i]);
                    }
                    if (del != null)
                    {
                        diDel.Add(SqlIDList[i], del[i]);
                    }
                    if (CheckScript.Count != 0)
                    {
                        for (int ci = 0; ci < CheckScript.Count; ci++)
                        {
                            System.Collections.Generic.List<string> cs = CheckScript[ci].Split(new char[]
							{
								';'
							}).ToList<string>();
                            diCheck.Add(SqlIDList[i], cs);
                        }
                    }
                }
                stdquery.GetType().GetProperty("Add").SetValue(stdquery, diAdd, null);
                stdquery.GetType().GetProperty("Modify").SetValue(stdquery, diModify, null);
                stdquery.GetType().GetProperty("Del").SetValue(stdquery, diDel, null);
                stdquery.GetType().GetProperty("Check").SetValue(stdquery, diCheck, null);
            }
        }
        private static void LoadReceiptsConfig(string module, ReceiptsConfigObject rco)
        {
            ReceiptsConfig rc = new ReceiptsConfig(module);
            rco.StdQuery = new ReceiptsConfigObject.ReceiptsConfigStdQuery();
            string modulescript = rc.IniScript;
            if (!(modulescript == "") && modulescript.Trim().Length != 0)
            {
                rco.StdQuery = new ReceiptsConfigObject.ReceiptsConfigStdQuery();
                rco.DataObject = new ReceiptsConfigObject.ReceiptsConfigDataObject();
                SmartPage.Test(rco, rc, modulescript, "StdQuery");
                SmartPage.Test(rco, rc, modulescript, "DataObject");
                string urlparamscript = rc.GetPrivateProfileString("URLPARAM", "PARAM");
                string urlparamActionScript = rc.GetPrivateProfileString("URLPARAM", "ACTION");
                string urlparamPageScript = rc.GetPrivateProfileString("URLPARAM", "PAGE");
                string common = rc.GetPrivateProfileString("COMMON", "COMMONNO");
                if (common != null && common.Length != 0)
                {
                    rco.Common = common.Split(new char[]
					{
						';'
					}).ToList<string>();
                    rco.Common.Remove("");
                }
                rco.UrlParam = new System.Collections.Generic.List<string>();
                if (urlparamscript != null && urlparamscript.Length != 0)
                {
                    rco.UrlParam = urlparamscript.Split(new char[]
					{
						';'
					}).ToList<string>();
                }
                if (urlparamActionScript != null && urlparamActionScript.Length != 0)
                {
                    rco.UrlParam.AddRange(urlparamActionScript.Split(new char[]
					{
						';'
					}).ToList<string>());
                }
                if (urlparamPageScript != null && urlparamPageScript.Length != 0)
                {
                    rco.UrlParam.AddRange(urlparamPageScript.Split(new char[]
					{
						';'
					}).ToList<string>());
                }
                rco.Business = rc.GetSection("BUSINESS");
            }
        }
    }
}
